// background.js

// 录制状态
let isRecording = false;
let recordingResult = '';
let recordCount = 0;

// 监听快捷键
chrome.commands.onCommand.addListener((command) => {
    if (command === "copy-info") {
        chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
            chrome.tabs.sendMessage(tabs[0].id, { action: "extractAndCopy" });
        });
    }
});

// 监听 content.js 和 popup 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "recordResult") {
        if (isRecording && request.data) {
            recordingResult += request.data;
            recordCount++;
            console.log('📊 累计记录:', recordCount);

            // ✅ 关键：告诉 content.js 当前条数
            sendResponse({ success: true, currentCount: recordCount });
        } else {
            sendResponse({ success: false });
        }
        return true; // 保持消息通道开放（用于异步 sendResponse）
    }
    else if (request.action === "startRecording") {
        // 来自 popup：开始录制
        isRecording = true;
        recordingResult = '';
        recordCount = 0;
        console.log('⏺️ 开始录制');
    }
    else if (request.action === "stopRecording") {
        // 来自 popup：停止录制
        isRecording = false;
        const result = recordingResult.trim();
        const count = recordCount;
        // 重置
        recordingResult = '';
        recordCount = 0;
        console.log('⏹️ 停止录制，共', count, '条');
        // 返回结果给 popup
        sendResponse({ success: true, data: result, count: count });
    }
    else if (request.action === "getRecordingStatus") {
        // 来自 popup：获取当前状态
        sendResponse({ isRecording });
    }
});